import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../logger.dart';

class BaseRefresherController {
  BaseRefresherController({
    required this.apiFn,
  });

  final Function(int pageIndex) apiFn;

  List<dynamic> dataList = <dynamic>[];

  int pageIndex = 1;

  Future<void> onRefresh({required RefreshController refreshCtrl}) async {
    pageIndex = 1;
    try {
      final dynamic value = await apiFn(pageIndex);

      if (value != null) {
        refreshCtrl.loadComplete();
        final getValue = value == null ? <dynamic>[] : value as List<dynamic>;

        dataList
          ..clear()
          ..addAll(getValue);

        refreshCtrl.refreshCompleted(resetFooterState: true);
      } else {
        refreshCtrl.refreshFailed();
      }
    } catch (e, s) {
      CoreKitLogger().e('BaseRefresherController onRefresh apiFn', e, s);
      refreshCtrl.refreshFailed();
    }
  }

  Future<void> onLoading({required RefreshController refreshCtrl}) async {
    final nextPage = pageIndex + 1;
    try {
      final dynamic value = await apiFn(nextPage);
      if (value != null) {
        final getValue = value == null ? <dynamic>[] : value as List<dynamic>;
        if (getValue.isNotEmpty) {
          dataList.addAll(getValue);
        }
        pageIndex = nextPage;
        refreshCtrl.loadComplete();
      } else {
        refreshCtrl.loadNoData();
      }
    } catch (e, s) {
      CoreKitLogger().e('BaseRefresherController onRefresh apiFn', e, s);
      refreshCtrl.refreshFailed();
    }
  }
}
